import React, { useEffect, useMemo, useRef, useState } from 'react'
import {
  ProCard,
  ProDescriptions,
  ProTable,
  TableDropdown,
  ProFormText,
  ProForm,
  ProFormDigit,
  ProFormTextArea,
  ProFormDependency,
  ProFormSelect,
  PageLoading,
  ModalForm
} from '@ant-design/pro-components';
import { PlusOutlined } from '@ant-design/icons';
import {
  Tabs,
  Input,
  List,
  Avatar,
  Row,
  Col,
  Space,
  AutoComplete,
  Divider,
  Select,
  Button,
  message,
  Empty,
  Card,
  Popover,
  InputNumber,
  Image
} from 'antd'
import type { TabsProps } from 'antd';
import type { ProFormInstance } from '@ant-design/pro-components';

import classnames from 'classnames';
import Camera from '@/components/Camera'
import PatientList from '@/components/PatientList'
import PulseInfoCalibration from '@/components/PulseInfoCalibration';
import IllnessList from '@/components/IllnessList'
import QuestionTerm2 from '@/components/QuestionTerm2'
import TongueCalibration from '@/components/TongueCalibration'
import MedicalRecord from '@/components/MedicalRecord';
import Consultation from '@/components/Consultation'
import Diagnosis from '@/components/Diagnosis';
import WesternMedicine from '@/components/WesternMedicine'
import PopoverItem from './components/PopoverItem'
import CheckListButton from '@/components/CheckListButton'


import AddModal from '@/components/Diagnosis/components/AddModal'

import { reqSeniorInquiryPrescriptionMedication } from '@/services/firstConsultation';
import { genderSchema, patientStatusSchema } from '@/utils/schema'
import { arrayFormatObj } from '@/utils'

import defImg from '@/static/images/header.png';

import {
  reqPatientList,
  reqDetal,
  reqUpdate,
  reqPulseUpdate,
  reqPulseDetail,
  reqPulseList,
  reqQuestionTermList,

} from '@/services/basicConsultation';


// reqSeniorInquiryList,
import {
  reqPulseCalibrationList,
  reqTongueCalibrationList,
  reqDiagnosisTermList,
  reqDiagnosisTermListByGrade,
  reqSeniorInquiryList,
  reqSeniorInquiryUpdate,
  reqSymptomList,
  reqSymptomListByGrade,
  reqBaseBodyAcupointList
} from '@/services/firstConsultation';

import styles from './index.module.less'

const { Search } = Input;

const getRandomInt = (max: number, min = 0) => Math.floor(Math.random() * (max - min + 1)) + min;

const searchResult = (query: string) =>
  new Array(getRandomInt(5))
    .join('.')
    .split('.')
    .map((_, idx) => {
      const category = `${query}${idx}`;
      return {
        value: category,
        label: (
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <span>
              找到 {query} 在{' '}
              <a
                href={`https://s.taobao.com/search?q=${query}`}
                target="_blank"
                rel="noopener noreferrer"
              >
                {category}
              </a>
            </span>
            <span>{getRandomInt(200, 100)} results</span>
          </div>
        ),
      };
    });


const Id = () => {

  const listRef = useRef()
  const [formObj] = ProForm.useForm()
  const modalFormRef = useRef<ProFormInstance>();

  // 患者搜索字段
  const [searchKey, setSearchKey] = useState('')

  const [update, setUpdate] = useState(0)

  // 当前问诊用户
  const [user, setUser] = useState<any>(null)

  // 当前用户问诊详情数据
  const [medicalCase, setMedicalCase] = useState<any>(null)


  console.log('当前用户问诊详情数据 :>> ', medicalCase);

  const [loading, setLoading] = useState(false)

  const [type, setType] = useState(0);
  const [acpOpen, setAcpOpen] = useState(false);
  const [acpconfirmnum, setAcpconfirmnum] = useState(0);
  const [acpnum, setAcpnum] = useState(0);

  // 当前问诊用户
  const [isShow, setIsShow] = useState<boolean>(false)
  async function handleShowModal(bool: boolean, isUpUser: boolean) {
    if (isUpUser) {
      setLoading(true)
      await getDetal(user?.id)
      setLoading(false)
    }
    setIsShow(bool)
  }

  // 更新用户数据
  async function upDataUser() {
    setLoading(true)
    await getDetal(user?.id)
    setLoading(false)
  }

  const readonly = user?.status == 3;

  console.log('user?.status=== :>> ', user?.status);

  const items = [
    // {
    //   key: '1',
    //   label: '基本问诊信息',
    //   disabled: true
    // },
    {
      key: '2',
      label: '脉诊标定',
      children: <PulseInfoCalibration readonly={readonly} user={medicalCase} upDataInfo={upDataInfo} />,
    },
    {
      key: '3',
      label: '舌诊标定',
      children: <TongueCalibration readonly={readonly} user={medicalCase} upDataInfo={upDataInfo} />

      ,
    },
    {
      key: '4',
      label: '基本问诊',
      children:
        <QuestionTerm2 readonly={readonly} user={medicalCase} upDataInfo={upDataInfo2} />,
    },
    {
      key: '5',
      label: '检测报告',
      children:
        <div className={styles.reportPicBox}>
          <Image width={'20%'} src={medicalCase?.reportPic} alt='检测报告' />
        </div>,
    },
    {
      key: '6',
      label: '病史',
      children:
        <Space >
          <div style={{ minHeight: 200 }}>{medicalCase?.medicalHistory}</div>
        </Space>,
    },
  ];

  // 选择问诊用户
  async function onSelectList(item: any) {
    setLoading(true)
    await getDetal(item?.id)
    setUser(item)
    setLoading(false)
  }

  async function onSubmit(item: any) {
    await upDataInfo2({ status: 3 });
    setSearchKey('')
    setUser(null)
    setUpdate(prv => prv + 1)
  };

  function openACP() {
    setAcpOpen(true);
  }
  async function closeACP() {
    setAcpOpen(false);
    console.log("acpnum>>>>>>>", acpnum)
    if (!acpnum || acpnum == 0) {
      setAcpnum(3)
      setAcpconfirmnum(3);
    } else {
      setAcpconfirmnum(acpnum);
    }
    let quantity = acpnum;
    if (!quantity || quantity == 0) quantity = 3;
    await reqSeniorInquiryPrescriptionMedication({
      "id": medicalCase?.seniorInquiry?.id,
      "medicineType": 3,
      "medicineList": [
        {
          "medicineId": 1,
          "quantity": quantity
        }
      ]
    });
  }
  function acpOnchange(num: number) {
    setAcpnum(num);
  }

  console.log('searchKey :>> ', searchKey);

  const listItems = [
    {
      key: '2',
      label: '待就诊',
      children:
        <PatientList
          status=''
          type='2'
          update={update}
          searchKey={searchKey}
          onSelect={(item: any) => onSelectList(item)}
          onPush={(item: any) => onSubmit(item)}
        />
      ,
    },
    {
      key: '3',
      label: '已完成',
      children:
        <PatientList
          status='3'
          type='2'
          update={update}
          searchKey={searchKey}
          onSelect={(item: any) => onSelectList(item)} onPush={undefined} />
      ,
    },

  ];


  // 病历信息详情(基础+高级问诊)
  async function getDetal(id: number | string) {
    try {
      const res = await reqDetal({
        id
      })
      console.log('病历信息详情 :>> ', res?.data);
      if (res?.resultCode == '00000000') {

        // setData(res?.data?.result)
        let medicalCase = res?.data;
        // let projectList = medicalCase?.projectList;
        // if (projectList) {
        //   let quantity = projectList[0]?.quantity;
        //   setAcpconfirmnum(quantity);
        // } else {
        //   setAcpconfirmnum(0);
        // }


        setMedicalCase(medicalCase)
      } else {
        message.error(`病历信息详情出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('病历信息详情出错！', error)
      console.log('病历信息详情出错！ :>> ', error);
    }
  }

  // 更改高级问诊信息
  async function upDataInfo(params: object) {
    try {
      const res = await reqSeniorInquiryUpdate({
        id: medicalCase?.seniorInquiry?.id,
        ...params
      })

      console.log('更改高级问诊信息 :>> ', res?.data);
      if (res?.resultCode == '00000000') {
        // setData(res?.data?.result)
        await getDetal(medicalCase.id)
        message.success(`更改高级问诊信息成功`)
      } else {
        message.error(`更改高级问诊信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('更改高级问诊信息出错！', error)
      console.log('更改高级问诊信息出错！ :>> ', error);
    }
  }


  // 更改基础问诊信息
  async function upDataInfo2(params: object) {
    try {
      const res = await reqUpdate({
        id: medicalCase.id,
        illnessNameHistory: medicalCase.illnessNameHistory,
        basicInquiryJson: medicalCase.basicInquiryJson,
        tonguePic: medicalCase.tonguePic,
        reportPic: medicalCase.reportPic,
        medicalHistory: medicalCase.medicalHistory,
        status: medicalCase.status,
        ...params
      })

      console.log('更改问诊信息信息 :>> ', res?.data);
      if (res?.resultCode == '00000000') {
        // setData(res?.data?.result)
        await getDetal(medicalCase.id)
        message.success(`更改问诊信息成功`)
      } else {
        message.error(`更改问诊信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('更改问诊信息出错！', error)
      console.log('更改问诊信息出错！ :>> ', error);
    }
  }





  // const handleSearch = (value: string) => {
  //   // setOptions(value ? searchResult(value) : []);
  // };

  // 搜索患者列表
  function onSearchSelect(value: string) {
    console.log('onSearchSelect=== :>> ', value);
    setSearchKey(value)
  }


  // const onSubmit = async () => {
  //   await upDataInfo({ status: 3 });

  // };

  const sexObj = arrayFormatObj(genderSchema.options);

  const patientStatus = arrayFormatObj(patientStatusSchema.options);


  const [baseBodyAcupointList, setBaseBodyAcupointList] = useState([])

  async function getBaseBodyAcupointList() {
    const errLogName = '穴位列表'
    try {
      const res = await reqBaseBodyAcupointList({
        pageNum: 1,
        pageSize: 10,
        type: 2
      })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        const mapArr = res?.data?.result?.map((item: any) => ({
          label: item?.name,
          value: item?.id
        }))
        setBaseBodyAcupointList(mapArr)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }

  useEffect(() => {
    getBaseBodyAcupointList()
  }, [])


  const baseBodyAcupointListMap = useMemo(() => {
    let obj = {};
    baseBodyAcupointList?.map((item: any) => {
      obj[item.value] = item
    })
    return obj
  }, [baseBodyAcupointList])


  // 添加针灸
  async function addZJ(values: any) {

    const baseBodyAcupointList = values?.baseBodyAcupoint?.map((item) => {
      if (baseBodyAcupointListMap && baseBodyAcupointListMap[item]) {
        return {
          tyBaseBodyAcupointId: baseBodyAcupointListMap[item]?.value,
          tyBaseBodyAcupointName: baseBodyAcupointListMap[item]?.label,
        }
      }
    })

    const errLogName = '针灸治疗'
    try {
      const res = await reqSeniorInquiryPrescriptionMedication({
        id: medicalCase?.seniorInquiry?.id,
        // 药类型，[1:中药，2:西药，3:项目]
        medicineType: 3,
        medicineList: [{
          medicineId: 1,
          quantity: values?.quantity,
          baseBodyAcupointList
        }],
      });
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        upDataUser();
        message.success(`${errLogName}保存成功！`)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }


    // message.success('提交成功');
    return true;
  }


  // useEffect(() => {
  //   if (Array.isArray(medicalCase?.projectList) && medicalCase?.projectList[0]?.quantity) {
  //     console.log('medicalCase?.projectList0000)))))))))))))))))))) :>> ', modalFormRef?.current);
  //     modalFormRef?.current?.setFieldValue('quantity', medicalCase?.projectList[0]?.quantity)
  //   }
  // }, [medicalCase?.projectList])


  function onInit(values, form) {
    if (Array.isArray(medicalCase?.projectList) && medicalCase?.projectList[0]?.quantity) {
      form.setFieldValue('quantity', medicalCase?.projectList[0]?.quantity)
      let baseBodyAcupoint = medicalCase?.baseBodyAcupointList.map((item) => item?.tyBaseBodyAcupointId)
      form.setFieldValue('baseBodyAcupoint', baseBodyAcupoint)
    }
  }
  // console.log('sexObj :>> ', user?.gender, (user?.gender || user?.gender == 0) && sexObj[user?.gender]?.label);

  return (
    <div className={styles.main}>
      <div className={styles.left}>
        {/* <AutoComplete
            // popupMatchSelectWidth={252}
           
            options={options}
            onSelect={onSearchSelect}
            onSearch={handleSearch}
          > */}
        <Input.Search
          size="large"
          style={{ width: '100%', marginBottom: 20, border: 'none' }}
          placeholder="患者姓名/手机号/身份证号码"
          enterButton='查询'
          allowClear
          onSearch={onSearchSelect}
          onPressEnter={(e) => onSearchSelect(e?.target?.value)}
        />
        <Tabs
          defaultActiveKey=""
          items={listItems}
          onChange={() => setUpdate(prev => prev + 1)}
        />
      </div>
      <div className={styles.right}>
        {
          user ?
            (

              <>
                <Space size={16}
                  direction="vertical"
                  className={classnames(styles.commonMar, styles.userWrap)}
                >
                  <Space size={16}>
                    <Avatar
                      size={{ xs: 32, sm: 32, md: 80, lg: 80, xl: 80, xxl: 80 }}
                      src={user?.avatar || defImg}
                    />
                    <Space direction="vertical">
                      <div>姓名:{user?.tyPatientName}</div>
                      <div>性别:{(user?.gender || user?.gender == 0) && sexObj[user?.gender]?.label}</div>
                      <div>
                        <Space size={24}>
                          <div>手机: {user?.phoneNum}</div>
                          <div>身份证号:{user?.cardId}</div>
                          <div>预约时间:{user?.appointTime}</div>
                          <div>就诊状态:{user?.status && patientStatus[user?.status]?.label}</div>
                          {/* <div>针灸治疗:{
                        (Array.isArray(medicalCase?.projectList) && medicalCase?.projectList[0]?.quantity) || 0
                      }次</div> */}
                        </Space>
                      </div>
                    </Space>

                  </Space>
                </Space>
                <div>
                  {!loading ?
                    <>
                      <MedicalRecord user={medicalCase} />
                      <div className={styles.proCardWrap}>
                        <div className={classnames(styles.noPadding, styles.cententWrap)} >
                          <Consultation
                            user={medicalCase}
                            upDataInfo={upDataInfo}
                            consultationReadonly={readonly}
                          />

                          <Card
                            type="inner"
                            title="诊断"
                            extra={!readonly && <Button className='commonOk' onClick={() => handleShowModal(true)}>编辑</Button>}
                          >
                            <Diagnosis
                              user={medicalCase}
                              upDataInfo={upDataInfo}
                            />
                          </Card>
                          {
                            isShow &&
                            <AddModal
                              isShow={isShow}
                              handleShowModal={handleShowModal}
                              user={medicalCase}
                              upDataInfo={upDataInfo}
                            />
                          }
                          <Card
                            type="inner"
                            title="开方"
                            extra={
                              !readonly && <Space>
                                <WesternMedicine
                                  user={medicalCase}
                                  upDataInfo={upDataInfo}
                                  upDataUser={upDataUser}
                                />
                              </Space>

                            }
                          >
                            <ProCard className={styles.noPadding}>
                              {
                                medicalCase?.westernMedicineList &&
                                Array.isArray(medicalCase?.westernMedicineList) &&
                                <ProCard className={styles.noPadding}>
                                  <h3>西药列表</h3>
                                  <div>
                                    <Space>
                                      {
                                        medicalCase?.westernMedicineList.map((item: any, index: number) => (
                                          <div key={index}>{item?.medicineName} {item?.quantity}</div>
                                        ))
                                      }
                                    </Space>
                                  </div>
                                </ProCard>
                              }
                              {
                                medicalCase?.medicineTake &&
                                <ProCard className={styles.noPadding}>
                                  <h3>汤剂信息</h3>
                                  <div>汤剂名:{medicalCase?.medicineTake?.tyBaseFormulaName}</div>
                                  <div>服药时间:{medicalCase?.medicineTake?.administrationTime}天</div>
                                  <div>用药剂量:{medicalCase?.medicineTake?.quantity}剂</div>
                                  <div>一剂几包:{medicalCase?.medicineTake?.packets}包</div>
                                  <div>服药间隔:{medicalCase?.medicineTake?.administrationInterval}天</div>
                                  <div>煮药时长:{medicalCase?.medicineTake?.cookingTime}分钟</div>
                                  <div>给患者备注:{medicalCase?.medicineTake?.toPatientRemark}</div>
                                  <div>给药房备注:{medicalCase?.medicineTake?.toMedicineStoreRemark}</div>
                                  {
                                    Array.isArray(medicalCase?.herbList) &&
                                    <div>
                                      <Space wrap>
                                        {
                                          medicalCase?.herbList.map((item: any, index: number) => (
                                            <div key={index}>{item?.medicineName} {item?.quantity}g</div>
                                          ))
                                        }
                                      </Space>
                                    </div>
                                  }
                                </ProCard>
                              }
                            </ProCard>
                          </Card>
                        </div>
                        <div className={styles.rightList}>
                          <div>
                            <h3 className={styles.rightName}>基本问诊信息</h3>
                            {
                              items.map((item, index) => (
                                <div key={index}>
                                  <PopoverItem
                                    data={item}
                                    content={item?.children}
                                  />
                                </div>
                              ))
                            }
                          </div>
                        </div>
                      </div>
                    </>
                    :
                    <PageLoading />
                  }
                </div>

              </>

            )
            : <></>
        }
      </div>
    </div>
  )
}

export default Id